local isServerAlive = true

function connect_server()
    for i = 1, #proxy.backends do
        local s = proxy.backends[i]
        print ("s.state:" + s.state)
        if s.state ~= proxy.BACKEND_STATE_DOWN then
            proxy.connection.backend_ndx = i
            print ("connecting to " .. i)
            return
        end
    end
end

function read_query(packet)
    for i = 1, #proxy.backends do
        local s = proxy.backends[i]
        print ("s.state:" + s.state)
        if s.state ~= proxy.BACKEND_STATE_DOWN then
            proxy.connection.backend_ndx = i
            print ("connecting to " .. i)
            return
        end
    end
end

function read_query(packet)
    if not isServerAlive then
        -- 如果服务端宕机，则暂停发送
        return proxy.PROXY_SEND_RESULT
    end

    if packet:byte() == proxy.COM_QUERY then
        local sql = packet:sub(2)
        local statements = splitSqlStatements(sql)

        for _, statement in ipairs(statements) do
            proxy.queries:append(1, string.char(proxy.COM_QUERY) .. statement)
        end

        return proxy.PROXY_SEND_QUERY
    end
end

function splitSqlStatements(sql)
    local statements = {}
    for statement in string.gmatch(sql, "[^;]+") do
        table.insert(statements, statement)
    end

    return statements
end

function read_ok_packet(packet)
    -- 服务端正常响应时将状态设置为活跃
    isServerAlive = true
end

function read_error_packet(packet)
    -- 服务端错误响应时将状态设置为宕机，并暂停发送
    isServerAlive = false
    return proxy.PROXY_SEND_RESULT
end

function connect_server()
    if proxy.global.backends[1].state == proxy.BACKEND_STATE_DOWN then
        isServerAlive=false
        print("Now Server down...")
    else
        proxy.connection.backend_ndx = 1
        print ("Now Connecting: " .. proxy.global.backends[proxy.connection.backend_ndx].dst.name)
    end
end



